import { showToast } from "@nutui/nutui";
import { onUnmounted, reactive, computed } from "vue";
import { $saleAchievementMobileCode } from "@/api/api";
import _ from "lodash";
export default (config?: any) => {
  // 状态
  const state = reactive({
    // 倒计时时长
    timedown: config?.timedown || 60,
    // 当前倒计时
    countdown: 0,
    // 倒计时定时器
    interval: null,
    // 第一次发送
    is_first: true,
    // 短信key
    key: '',
  } as any)
  // 发送短信
  const sendSms = _.debounce((mobile: string, code: string, index_code: string, errorCallback: Function) => {
    if (state.countdown > 0) {
      return;
    }
    if (!mobile) {
      showToast.fail('请输入手机号!');
      return;
    }
    if (mobile.length !== 11) {
      showToast.fail('手机号格式不正确!');
      return;
    }
    if (!code) {
      showToast.fail('请输入图文验证码!');
      return;
    }
    let params = {
      mobile,
      keywords: 'MOBILE_VERIFY_CODE',
      code,
      index_code,
      scene: "login",
    }
    $saleAchievementMobileCode(params).then((res: any) => {
      state.key = res.data.key;
      showToast.success('短信发送成功');
      startCountDown();
    }).catch((err: any) => {
      errorCallback();
    })
  }, 300, { leading: true, trailing: false })
  // 开始倒计时
  const startCountDown = () => {
    state.countdown = state.timedown;
    state.interval = setInterval(() => {
      if (state.countdown > 0) {
        state.countdown--;
      } else {
        state.is_first = false;
        clearInterval(state.interval);
      }
    }, 1000)
  }
  // 显示文字
  const show_text = computed(() => {
    // 倒计时结束
    const end_text = state.is_first ? '发送验证码' : '重新发送';
    // 倒计时中
    const doing_text = `${state.countdown}s`;
    return state.countdown > 0 ? doing_text : end_text;
  })
  // 验证码格式验证
  const valid = (verify_code: string) => {
    if (!verify_code) {
      return '请输入手机验证码!';
    } else if (verify_code.length !== 6) {
      return '请输入6位手机验证码!';
    } else {
      return '';
    }
  }
  onUnmounted(() => {
    clearInterval(state.interval);
  })
  return {
    state,
    show_text,
    sendSms,
    valid,
  }
}